<template>
  <div class="field-container">
    <section class="top">
      <div class="title">
        <PmBreadcrumb />
        <span style="font-weight: 400; font-size: 18px; line-height: 22px"
          >项目模版</span
        >
        <el-icon size="10" style="margin: 0 6px"><ArrowRight /></el-icon>
        <span>{{ route.query.name }}</span>
      </div>
      <div style="display: flex; gap: 12px">
        <!--        <el-input-->
        <!--          v-model="input2"-->
        <!--          class="responsive-input"-->
        <!--          placeholder="请输入关键词搜索"-->
        <!--          :prefix-icon="Search"-->
        <!--        />-->
        <!--        <el-button type="primary" :icon="Plus">添加字段</el-button>-->
      </div>
    </section>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="基本信息" name="baseInfo"></el-tab-pane>
      <el-tab-pane label="角色权限" name="roles"></el-tab-pane>
      <el-tab-pane label="生命周期" name="lifecycle"></el-tab-pane>
      <el-tab-pane label="任务类型" name="fourth"></el-tab-pane>
      <el-tab-pane label="任务wbs" name="fourth"></el-tab-pane>
      <el-tab-pane label="流程策划" name="fourth"></el-tab-pane>
    </el-tabs>

    <div class="content" v-if="activeName === 'baseInfo'">
      <div class="form-content">
        <div class="templateForm">
          <el-form :model="formData" label-width="120" label-position="left">
            <el-form-item prop="name" label="模板名称">
              <el-input
                maxlength="50"
                show-word-limit
                v-model="formData.name"
                placeholder="请输入模板名称"
              />
            </el-form-item>
            <el-form-item prop="remark" label="描述">
              <el-input
                type="textarea"
                :rows="4"
                v-model="formData.remark"
                maxlength="100"
                show-word-limit
                placeholder="请输入模板名称"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="cover-container">
          <el-upload
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-change="handleAvatarChange"
            accept="image/*"
            :auto-upload="false"
            ref="uploadRef"
          >
            <div style="display: flex; flex-direction: column; gap: 16px">
              <div class="cover-uploader">
                <img
                  v-if="formData.cover"
                  :src="formData.cover"
                  class="cover"
                />
                <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
              </div>
              <el-button @click="changeCover">更改封面</el-button>
            </div>
          </el-upload>
        </div>
      </div>
      <el-button @click="handleSaveTemplate" class="save-btn" type="primary"
        >保存</el-button
      >
    </div>
    <div class="content" v-if="activeName === 'roles'">
      <el-row style="height: 100%; border: 1px solid #e5e7eb">
        <el-col :span="4">
          <ProjectRoleList
            ref="ProjectRoleListRef"
            v-if="templateInfo.projectId"
            :projectId="templateInfo.projectId"
            @getRolePermission="getRolePermission"
          ></ProjectRoleList>
        </el-col>
        <el-col :span="20">
          <ProjectRoleSetting
            ref="ProjectRoleSettingRef"
            v-if="currentRoleId"
            :roleId="currentRoleId"
            @refresh="refresh"
          ></ProjectRoleSetting>
        </el-col>
      </el-row>
    </div>
    <div class="content" v-if="activeName === 'lifecycle'">
      <editLifecycle
        :lifecycleId="projectDetail?.lifecycleModel?.dataId || ''"
        mode="preview"
        v-if="projectDetail?.lifecycleModel?.dataId"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
  import { nextTick, onMounted, reactive, ref } from "vue";
  import { Plus, Search, ArrowRight } from "@element-plus/icons-vue";
  import { useRoute } from "vue-router";
  import {
    ElMessage,
    type TabsPaneContext,
    type UploadProps,
    type UploadFile,
  } from "element-plus";
  import PmBreadcrumb from "@/components/PmBreadcrumb.vue";
  import ProjectRoleList from "@/views/pm/components/projectRoleList.vue";
  import ProjectRoleSetting from "@/views/pm/components/projectRoleSetting.vue";
  import { getPmTempInfo, updatePmTemp } from "@/api/pm/pmTemplate.ts";
  import { projectOverviewAJAX } from "@/api/project.ts";
  import type { pmTemplateVORes } from "@/interface/pm/pmTemplate.ts";
  import { convertFileToBase64 } from "@/utils/common.ts";
  import type { projectRoleVo } from "@/interface/pm/projectRole.ts";
  import editLifecycle from "@/views/pm/globalSetting/globalLifecycle/lifecycle/editLifecycle.vue";
  import type { ProjectOverviewResponse } from "@/interface/pm/baseInfo.ts";

  const handleClick = (tab: TabsPaneContext, event: Event) => {
    console.log(tab, event);
  };
  const activeName = ref("baseInfo");
  const currentRoleId = ref("");
  const ProjectRoleListRef = ref(null);
  const ProjectRoleSettingRef = ref(null);
  const route = useRoute();
  const uploadRef = ref(null);
  const templateInfo = ref<pmTemplateVORes>({});
  const projectDetail = ref<ProjectOverviewResponse>(
    {} as ProjectOverviewResponse,
  );

  const formData = reactive({
    name: "",
    remark: "",
    cover: "",
  });

  const imageUrl = ref("");

  const handleAvatarSuccess: UploadProps["onSuccess"] = (
    response,
    uploadFile,
  ) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  };

  const handleAvatarChange = (uploadFile: UploadFile) => {
    console.log("handleAvatarChange", uploadFile.raw);
    convertFileToBase64(uploadFile.raw).then((res) => {
      console.log(res);
      formData.cover = res as string;
    });
  };
  const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
    if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error("Avatar picture size can not exceed 2MB!");
      return false;
    }
    console.log(rawFile);
    return true;
  };

  const getPmTemplateInfo = async () => {
    const res = await getPmTempInfo(route.query.id as string);
    templateInfo.value = res;
    formData.name = res.name?.zh_CN || "";
    formData.remark = res.remark || "";
    formData.cover = res.cover || "";
  };
  const changeCover = () => {
    console.log(uploadRef.value);
  };
  const handleSaveTemplate = async () => {
    const params: pmTemplateVORes = {
      id: templateInfo.value.id,
      name: {
        zh_CN: formData.name,
      },
      remark: formData.remark,
      cover: formData.cover,
    };
    await updatePmTemp(params);
    ElMessage({
      type: "success",
      message: "保存成功",
    });
    getPmTemplateInfo();
  };

  const getProjectDetails = async () => {
    const res = await projectOverviewAJAX(templateInfo.value.projectId!);
    projectDetail.value = res;
  };
  const getRolePermission = (roleInfo: projectRoleVo) => {
    console.log("getRolePermission", roleInfo);
    currentRoleId.value = roleInfo.id!;
    nextTick(() => {
      ProjectRoleSettingRef.value?.getRoleSettings();
    });
  };
  const refresh = () => {
    ProjectRoleListRef.value?.getList();
  };
  onMounted(async () => {
    await getPmTemplateInfo();
    getProjectDetails();
  });
</script>

<style>
  .field-sort-popover {
    border-radius: 4px;
    padding: 8px !important;
    box-shadow: 0px 8px 10px -5px #00000014;
  }
  .cover-uploader {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    width: 128px;
    height: 128px;
    display: flex;
    flex-direction: column;
  }
  .cover {
    width: 100%;
    height: 100%;
  }

  .cover-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 128px;
    height: 128px;
    text-align: center;
  }
</style>

<style scoped lang="scss">
  .table-container {
    margin-top: 12px;
    height: calc(100vh - 180px);
  }

  .field-container {
    box-sizing: border-box;
    padding: 16px;
    height: 100%;
    display: flex;
    flex-direction: column;
    .top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .title {
        font-weight: 500;
        font-size: 18px;
        line-height: 22px;
      }
    }
    .content {
      flex: 1;
    }
  }

  .topAlert {
    margin-top: 12px;
    padding: 4px 12px;
    :deep(.el-alert__close-btn) {
      top: 8px;
      color: #1f2329;
    }
  }

  .demo-tabs {
    :deep(.el-tabs__item) {
      color: #5e5e5e;
    }
    :deep(.el-tabs__item.is-active, .el-tabs__item:hover) {
      color: #1aa1fb;
    }
  }

  .form-content {
    display: flex;
    margin-top: 12px;
    .templateForm {
      width: 600px;
    }
    .cover-container {
      display: flex;
      flex-direction: column;
      gap: 12px;
      padding: 0 12px;
      margin: 0 12px;
      border-left: 1px solid #ebeef5;
      //height: 175px;
    }
  }
  .save-btn {
    margin-left: 120px;
    width: 120px;
  }
</style>
